﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Threading;
//using System.Security.Cryptography;
using SearchAlgorithms.Algorithms;
using SearchAlgorithms.Algorithms.Compare;
using SearchAlgorithms.Interfaces;
using SearchAlgorithms.Services;
using SearchAlgorithms;
using static SearchAlgorithms.Services.ConsoleBlock;


namespace BinaryComparison_1
{

    public partial class BinaryComparison : Form
    {
        //定义全局变量
        string SearchMethod;
        string CompareMethod;

        // 添加模块作为类的成员变量
        private FileReadBlock fileReadBlock1;
        private FileReadBlock fileReadBlock2;
        private SegmentBlock segmentBlock1;
        private SegmentBlock segmentBlock2;
        private IntegrateBlock integrateBlock1;
        private IntegrateBlock integrateBlock2;
        private CompareBlock compareBlock;
        private ConsoleResultBlock consoleResultBlock;

        public BinaryComparison()
        {
            InitializeComponent();
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            ChooseFile(textBox1);
        }

        private void label2_Click(object sender, EventArgs e)
        {

        }


        private void ChooseFile(TextBox textBox)
        {
            ofd = new OpenFileDialog();
            ofd.DefaultExt = "bin";
            DialogResult result = ofd.ShowDialog();

            if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(ofd.FileName))
            {
                textBox.Text = ofd.FileName.ToString();
            }
        }
        private void textBox_TextChanged(object sender, EventArgs e)
        {
            var textBox = (TextBox)sender;
            if (File.Exists(textBox.Text))
            {
                textBox.ForeColor = Color.Green;
            }
            else
            {
                textBox.ForeColor = Color.Red;
            }

            if (File.Exists(textBox1.Text) && File.Exists(textBox2.Text) && File.Exists(textBox3.Text))
            {
                compare_button.Enabled = true;
            }
            else
            {
                compare_button.Enabled = false;
            }
        }

        private async void compare_button_Click(object sender, EventArgs e)
        {
            try
            {  
                //处理非法操作
                if (string.IsNullOrEmpty(textBox1.Text) || string.IsNullOrEmpty(textBox2.Text) || string.IsNullOrEmpty(textBox3.Text))
                {
                    MessageBox.Show("you must provide the paths to the files.", "Error");
                    return;
                }

                string filePathA = textBox1.Text;
                string filePathB = textBox2.Text;
                string FileCPath = textBox3.Text;
                byte[] pattern = File.ReadAllBytes(FileCPath);
                int bufferSize = 15;
                //设置默认算法
                if (comboBox1.SelectedIndex == -1)
                {
                    SearchMethod = "IndexOf";
                    comboBox1.Text = SearchMethod;
                }
                if (comboBox2.SelectedIndex == -1)
                {
                    CompareMethod = "Comparison";
                    comboBox2.Text = CompareMethod;
                }

                List<string> message = new List<string>();

                fileReadBlock1 = new FileReadBlock(filePathA, bufferSize);
                fileReadBlock2 = new FileReadBlock(filePathB, bufferSize);

                segmentBlock1 = new SegmentBlock(pattern, bufferSize, SearchMethod);
                segmentBlock2 = new SegmentBlock(pattern, bufferSize, SearchMethod);

                // 整合模块
                integrateBlock1 = new IntegrateBlock();
                integrateBlock2 = new IntegrateBlock();

                compareBlock = new CompareBlock(CompareMethod);
                consoleResultBlock = new ConsoleResultBlock();

                richTextBox1.Clear(); // 清空 RichTextBox

                fileReadBlock1.DataArrived += (data) =>
                {
                    segmentBlock1.Enqueue(data);
                };

                fileReadBlock2.DataArrived += (data) =>
                {
                    segmentBlock2.Enqueue(data);
                };

                segmentBlock1.DataArrived += (data) =>
                {
                    integrateBlock1.Enqueue(data);
                };
                segmentBlock2.DataArrived += (data) =>
                {
                    integrateBlock2.Enqueue(data);
                };

                integrateBlock1.DataArrived += (data) =>
                {
                    compareBlock.Enqueue_1(data);
                };
                integrateBlock2.DataArrived += (data) =>
                {
                    compareBlock.Enqueue_2(data);
                };

                compareBlock.DataArrived += (data) =>
                {
                    consoleResultBlock.Enqueue(data);
                   
                };

                consoleResultBlock.DataArrived += (data) =>
                {
                    foreach (var word in data)
                    {
                        message.Add(word);
                        UpdateRichTextBox(word);
                    }
                    
                };
                // 使用Task.Run来在后台线程上运行耗时的异步操作
                await Task.Run(async () =>
                {
                    Task readTask1 = Task.Run(() => fileReadBlock1.ReadBytes());
                    Task readTask2 = Task.Run(() => fileReadBlock2.ReadBytes());

                    // 异步等待文件读取任务完成
                    await readTask1;
                    await readTask2;
                    // 等待控制台输出块和分段块完成
                    await Task.WhenAll(
                        segmentBlock1._Process.Completion, segmentBlock2._Process.Completion, integrateBlock1._Process.Completion, integrateBlock2._Process.Completion, compareBlock.compareBlock.Completion,
                        consoleResultBlock._InputBlock.Completion
                    );
                });
               
                if (message.Count > 0)
                {
                    string messageBoxText = $"{message.Count} 帧不同.";
                    MessageBox.Show(messageBoxText, "Attention!");
                    //ShowRichTextBox(message);
                }
                else
                {
                    richTextBox1.Clear();
                    MessageBox.Show($"文件相同. ", "Attention!");
                }
            }
            catch (Exception ex)
            {
                // 异常处理
                MessageBox.Show($"An error occurred: {ex.Message}");
            }
        }

        //可以拖动文件到textBox
        private void textbox_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effect = DragDropEffects.Link;
        }

        private void textBox_DragDrop(object sender, DragEventArgs e)
        {
            var textBox = (TextBox)sender;
            string[] files = e.Data.GetData(DataFormats.FileDrop) as string[]; // get all files droppeds  
            if (files != null && files.Any())
                textBox.Text = files.First(); //select the first one  
        }

        private void browse2_button_Click(object sender, EventArgs e)
        {
            ChooseFile(textBox2);
        }

        private void browse3_button_Click(object sender, EventArgs e)
        {
            ChooseFile(textBox3);
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {

        }

        private void toolStripTextBox1_Click(object sender, EventArgs e)
        {

        }

        private void BinaryComparison_Load(object sender, EventArgs e)
        {

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void printPreviewDialog1_Load(object sender, EventArgs e)
        {

        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {

        }
        private void ShowRichTextBox(List<string> messages)
        {
            richTextBox1.Clear();
            richTextBox1.Text = string.Join(Environment.NewLine, messages);
        }
        private void UpdateRichTextBox(string message)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new Action<string>(UpdateRichTextBox), message);
            }
            else
            {
                richTextBox1.AppendText(message + Environment.NewLine);
            }
        }

        private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e)
        {
            SearchMethod = comboBox1.Text;
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            CompareMethod = comboBox2.Text;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            // 停止所有模块
            segmentBlock1._Process.Complete();
            segmentBlock2._Process.Complete();
            integrateBlock1._Process.Complete();
            integrateBlock2._Process.Complete();
            compareBlock.compareBlock.Complete();
            consoleResultBlock._InputBlock.Complete();
        }


    }
}
